<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/3 0003
 * Time: 09:09
 */
namespace app\home\controller\report;
use app\home\controller\Base;
use app\home\model\dealer\Dealer;
use app\home\model\dealer\Message;
use app\home\model\order\GoodsOrder;
use app\home\model\report\Detection;
use app\home\model\report\DetectionComment;
use app\home\model\report\DetectionOrder;
use app\home\model\report\Report;
use app\home\model\report\ReportGoods;
use app\home\service\CodeService;
use app\home\service\IdentityService;
use app\home\service\ReportService;
use app\home\service\TokenService;
use think\Db;
use think\Exception;

class Order extends Base
{
    protected $param=[];
    public function __construct()
    {
        $this->param = input('post.');
    }

    /**测评详情信息
     * @return \think\response\Json
     */
    public function info(){

        try {
            if (request()->isPost()) {
                $dId = input("d_id");
                if(empty($dId))  return CodeService::ORDER_REPORT_ID;
                $info= Detection::where(["d_id"=>$dId])->find();
                if(empty($info)) return CodeService::ORDER_USER_REPORT_INFO;
                if($info["status"] === "N") return CodeService::PRODUCT_IS_OFFLINE;

                if(empty($info["question"]) || empty($info["introduces"])){
                    $Yidee  =new ReportService();
                    $result = $Yidee->question($info['items_id']);
                    if($result === false){
                        return CodeService::REPORT_GET_FULL;
                    }
                    $introduces["introduces"]      =$result["desc"];
                    $introduces["commentNum"]      =$result["commentNum"];
                    $introduces["questionNumber"]  =$result["questionNumber"];
                    $introduces["reportPages"]     =$result["reportPages"];
                    $introduces["visitNum"]        =$result["visitNum"];
                    $introduces["elapsedTime"]     =$result["elapsedTime"];
                    $introduces["testSource"]      =$result["testSource"];
                    Db::table('detection')
                        ->where(["d_id"=>$dId])
                        ->update([
                            "question"=>json_encode($result['questions']),
                            "introduces"=>json_encode($introduces)
                        ]);
                    $info["introduces"]=$introduces["introduces"];
                }else{
                    $introduces=json_decode($info["introduces"],true);
                }
                $info["introduces"]     =$introduces['introduces'];
                $info["commentNum"]     =$introduces['commentNum'];
                $info["questionNumber"] =$introduces['questionNumber'];
                $info["reportPages"]    =$introduces['reportPages'];
                $info["visitNum"]       =$introduces['visitNum'];
                $info["elapsedTime"]    =$introduces['elapsedTime'];
                return CodeService::response(200,CodeService::SUCCESS,$info);
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**创建订单
     * @return \think\response\Json
     */
    public function order(){
        try {
            $dealerInfo = parent::is_Login();
            if(!$dealerInfo){
                return CodeService::AUTH_TIMEOUT;
            }
            $dealerId            = $dealerInfo['u_id'];
            $dId = input("d_id");
            if(empty($dId))  return CodeService::ORDER_REPORT_ID;
            $info = Detection::where(["d_id"=>$dId])->find();
            if(empty($info))            return CodeService::ORDER_USER_REPORT_INFO;
            if($info["status"] === "N") return CodeService::PRODUCT_IS_OFFLINE;
            $DetectionOrder= new DetectionOrder();
            $relsult    = $DetectionOrder->detectionOrder($dealerId,$dId);
            if($relsult === false){
                return CodeService::ORDER_CREAT_FULL;
            }
            $orderNumber= $DetectionOrder->getOrderNumber();
            $Price      = $DetectionOrder->getPrice();
            Detection::where(["d_id"=>$dId])->setInc('buy_count');
            $data["order"] = $orderNumber;
            $data["money"] = $Price * 100;
            $data["id"]    = \db('detection')->where(['d_id'=>$dId])->value('items_id');
            return  CodeService::response(200,CodeService::SUCCESS,$data);
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }


    /**
     * @return \think\response\Json
     */
    public function question(){
            try {
            if (request()->isPost()) {
                $order = input("post.order");
                if(empty($order)){
                    return CodeService::ORDER_EMPTY_ID;
                }
                $order_info= DetectionOrder::where(["o_number"=>$order])->find();

                if($order_info["o_type"] == 1){
                    if($order_info["o_pay"] == 0) return CodeService::ORDER_USER_ORDER_NOPAY;
                    if($order_info["o_pay"] == 2) return CodeService::ORDER_USER_ORDER_REFUND;
                }
                if($order_info["o_pay"] == 3)       return CodeService::ORDER_YFG_FULL;
                if($order_info["o_execute"] == 1)   return CodeService::ORDER_YES_SUCCESS;
                if($order_info["o_state"] == "N")   return CodeService::ORDER_DELETE;

                $detection = Detection::where(["d_id"=>$order_info["d_id"]])->find();
                if(empty($detection["question"])){
                    $Yidee  =new ReportService();
                    $result = $Yidee->question($detection['items_id']);
                    if($result === false){
                        return CodeService::REPORT_GET_FULL;
                    }
                    Db::table('detection')
                        ->where(["d_id"=>$order_info["d_id"]])
                        ->update(["question"=>json_encode($result['questions'])]);
                    return CodeService::response(200,CodeService::SUCCESS,$result['questions']);
                }
                $question=json_decode($detection["question"],true) ;
                return CodeService::response(200,CodeService::SUCCESS,$question);

            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
                return CodeService::response(500,$msg);
        }
    }
    /**
     * 提交测评答案
     */
    public function answer(){

        try {
            if (request()->isPost()) {
                $Yidee  =new ReportService();
                $ffrom  = input("post.ffrom");
                $itemId = input("post.itemId");
                $answer = input("post.answer");
                $order  = input("post.order");//订单号

                if(empty($ffrom)){
                    return CodeService::ORDER_FFROM;
                }

                if(empty($order)){
                    return CodeService::ORDER_CODE;
                }

                if(empty($answer)){
                    return CodeService::ORDER_ANSWER;
                }

                $order_info = DetectionOrder::where(["o_number"=>$order])->find();
                $detection  =json_decode($order_info["o_detection_json"],true);
                if(empty($itemId)){

                    //MoguDetection::where(["d_id"=>$order_info["d_id"]])->find();
                    $itemId   =$detection["items_id"];
                    if(!$itemId) return CodeService::DATA_RESULT_REFUND;
                }
                if(empty($order_info)) return CodeService::ORDER_USER_ORDER_INFO;
                if($order_info["o_type"] == 1){
                    if($order_info["o_pay"] == 0) return CodeService::ORDER_USER_ORDER_NOPAY;
                    if($order_info["o_pay"] == 2) return CodeService::ORDER_USER_ORDER_REFUND;
                    $type='P';
                }else{
                    $type='F';
                }
                if($order_info["o_pay"] == 3)     return CodeService::ORDER_YFG_FULL;
                if($order_info["o_execute"] == 1) return CodeService::ORDER_YES_SUCCESS;

                $info_desc  = Db::table("detection_order_info")->where(["o_number"=>$order])->find();
                $uid        = $order_info["u_id"];
                $rel        = $Yidee->answer($itemId,$answer,$ffrom,$type,true,$uid);// false 测试数据, true正式数据
                $oi_report_info =json_encode($rel);
                if($rel === false || empty($rel)){
                    if(empty($info_desc) ){

                        Db::table("detection_order_info")->insert([
                            "o_id"      =>$order_info["o_id"],
                            "o_number"  =>$order_info["o_number"],
                            "oi_report_info"=>$oi_report_info,
                            "oi_answer"     =>$answer,
                            "oi_create_time"=>date("Y-m-d H:i:s",time())
                        ]);
                    }
                    Db::table("detection_order")->where(["o_number"=>$order])->update(["o_execute"=>2]);
                    if($rel === false){
                        return CodeService::response(5007,$Yidee->message);
                    }else{
                        return CodeService::response(200,CodeService::ORDER_TO_AGIN);
                    }
                }
                Db::startTrans();
                if(!empty($info_desc)){
                    $bool =  Db::table("detection_order_info")
                        ->where(["o_number"=>$order])
                        ->update([
                            "oi_report_info"=>$oi_report_info,
                            "oi_answer"     =>$answer,
                            "oi_update_time"=>date("Y-m-d H:i:s",time())
                        ]);
                }else{
                    $bool=  Db::table("detection_order_info")->insert([
                        "o_id"      =>$order_info["o_id"],
                        "o_number"  =>$order_info["o_number"],
                        "oi_report_info"=>$oi_report_info,
                        "oi_answer"     =>$answer,
                        "oi_create_time"=>date("Y-m-d H:i:s",time())
                    ]);
                }
                $message=new Message();
                if($bool != false){
                    $content="您于".date('Y-m-d H:i',strtotime($order_info['o_create_time']))."查询的".$detection['title']."已就绪";
                    $message->sendMessage($uid,1,$content,$order_info["o_id"]);
                    if($order_info["o_type"] == 2){ //如果是免费订单
                        $up_order['o_pay']          =1;//修改为已经支付的状态
                    }
                    $up_order['o_execute']      =1;
                    $up_order['o_execute_time'] =date("Y-m-d H:i:s",time());
                    Db::table("detection_order")
                        ->where(["o_number"=>$order])
                        ->update($up_order);
                    $idstr = $order_info["o_id"];
                    Db::commit();
                    return CodeService::response(200,CodeService::SUCCESS,["idstr"=>$idstr,"order"=>$order,"itemId"=>$itemId]);
                }else{
                    $content="您于".date('Y-m-d H:i',strtotime($order_info['o_create_time']))."查询的".$detection['title']."已就绪";
                    $message->sendMessage($uid,1,$content,$order_info["o_id"]);
                    Db::table("detection_order")->where(["o_number"=>$order])->update(["o_execute"=>2]);
                    Db::rollback();
                    return CodeService::REPORT_GET_FULL;
                }
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**获取到报告详情
     * @return \think\response\Json
     */
    public function report(){
        try {
            if (request()->isPost()) {
                $token = input("token");
                if(!empty($token)){
                    $dealerInfo=parent::is_Login();
                    if(!$dealerInfo){
                        return CodeService::AUTH_TIMEOUT;
                    }
                    $u_id       = $dealerInfo["u_id"];
                    $Dealer     = new Dealer();
                    $user       = $Dealer->where("u_id",$u_id)->field(["phone","nick_name","headimg",'dealer_code'])->find();
                }else{
                    $user       = [];
                }

                $order      = input("post.order");//订单编号
                $idstr      = input("post.idstr");//订单号
                $o_id       = $idstr;
                if(empty($order) && empty($o_id)) return CodeService::PARAMETER_EXCEPTION;
                if(!empty($order)){
                    $where["o_number"]=$order;
                }else if(!empty($o_id)){
                    $where["o_id"]    =$o_id;
                }
                $order_info = DetectionOrder::where($where)->find();
                if(empty($order_info)) return CodeService::ORDER_USER_ORDER_INFO;
                $info_desc  = Db::table("detection_order_info")->where($where)->find();
                if(!empty($info_desc)){
                    if(empty($info_desc["oi_report_info"]) || $info_desc["oi_report_info"] == 'null' || $info_desc["oi_report_info"] == false){
                        Db::table("detection_order")->where($where)->update(["o_execute"=>2]);
                        return CodeService::REPORT_GET_FULL;
                    }else{
                        Db::table("detection_order")
                            ->where($where)
                            ->update(['o_is_see'=>1]);
                        $report_info        = json_decode($info_desc["oi_report_info"],true);
                        if(!is_array($report_info)){
                            $report_info        = json_decode($report_info,true);
                        }

                        if($order_info["o_type"] == 2){ ///pages/Mush/otherreport/frepld?uid=XX&share=1
                            $url    ='#/pages/Mush/otherreport/frepld?d_id='.reversal($order_info['d_id'],1)."&share=1";
                        }else{
                            $url    ="#/pages/Mush/otherreport/sfrepld?d_id=".reversal($order_info['d_id'],1)."&share=1";
                        }
                        $report_info["url"]           = config('h5').$url;//分享链接
                        return CodeService::response(200,CodeService::SUCCESS,['user'=>$user,"report_info"=>$report_info]);
                    }
                }else{
                    return CodeService::ORDER_USER_REPORT_INFO;
                }
            }else{
                    return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function order_list(){
        try {
            if (request()->isPost()) {
                $dealerInfo=parent::is_Login();
                if(!$dealerInfo){
                    return CodeService::AUTH_TIMEOUT;
                }
                $user       = $dealerInfo;
                $u_id       = $user["u_id"];
                $listrow    = input('listrow');
                $page       = input('page');
                $c_id       = input('c_id');
                $oExecute   = input('o_execute');
                $page       = !empty($page)?$page:1;
                $listrow    = !empty($listrow)?$listrow:15;
                $where["u_id"]   =$u_id;
                $where["o_state"]="Y";
                $where["o_pay"]  =['in',[1,2]];
                if(!empty($c_id)){
                    if($c_id != "ALL"){
                        $where["c_id"]        =$c_id;
                    }
                };
                if(!empty($oExecute)) {
                    if($oExecute == "Y")  $where["o_execute"]   =1; //已查询
                    if($oExecute == "N")  $where["o_execute"]   =0; //未查询
                }
                $detectionOrder=new DetectionOrder();
                $detectionOrder->page   =$page;
                $detectionOrder->pageNum=$listrow;
                $order  =$detectionOrder->getPageList($where);
                return CodeService::response(200,CodeService::SUCCESS,$order);
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**删除订单
     * @return \think\response\Json
     */
    public function order_del(){
        try {
            if (request()->isPost()) {
                $dealerInfo=parent::is_Login();
                if(!$dealerInfo){
                    return CodeService::AUTH_TIMEOUT;
                }
                $user       =$dealerInfo;
                $u_id       = $user["u_id"];
                $order       = input('order');
                if(empty($order)) return CodeService::ORDER_CODE;

                $bool = Db::table("detection_order")
                    ->where(["o_number"=>$order,"u_id"=>$u_id])
                    ->update(["o_cancel_time"=>date("Y-m-d",time()),
                        "o_state"=>"N"]);
                if($bool !== false){
                    return CodeService::response(200,CodeService::OPERATE);
                }else{
                    return CodeService::response(300,CodeService::FULL);
                }
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**获取到评论
     */
    public function comment(){
        return [ "code" => 200,
            "msg"  => '获取成功',
            "data" => []];
        //ssss
//        try {
//            if (request()->isPost()) {
//                $dId        = input("d_id");
//                $page       = input("page");
//                $listrow    = input("listrow");
//                $page       =!empty($page)?$page:1;
//                $listrow    =!empty($listrow)?$listrow:15;
//                if(empty($dId))  return CodeService::ORDER_REPORT_ID;
//                $info= Detection::where(["d_id"=>$dId])->find();
//                if(empty($info)) return CodeService::ORDER_USER_REPORT_INFO;
////                $Comment = new DetectionComment();
////                $Comment->setApiComment($dId);
//                if($info["discuss"] === "Y"){ //如果关闭了评论就让他为空
//                    $comment=DetectionComment::where(["d_id"=>$dId])->page($page,$listrow)->select();
//                }else{
//                    $comment=[];
//                }
//                return CodeService::response(200,CodeService::SUCCESS,$comment);
//            }else{
//                return CodeService::REQUEST_METHOD_ERROR;
//            }
//        }catch (\Exception $e) {
//            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
//            return CodeService::response(500,$msg);
//        }
    }

    /**
     * @return \think\response\Json
     */
    public function assessment(){
        try {
            if (request()->isPost()) {
                $token=input("token");
                if(empty($token)){
                    $data=["is_see"=>"N","execute"=>"N","order"=>''];
                    return CodeService::response(200,CodeService::SUCCESS,$data);
                }
                $dealerInfo=parent::is_Login();
                if(!$dealerInfo){
                    return CodeService::AUTH_TIMEOUT;
                }
                $user       = $dealerInfo;
                $u_id       = $user["u_id"];
                $d_id       = input('d_id');
                if(empty($d_id)){
                    return CodeService::ORDER_REPORT_ID;
                }
                $detection  = Db::table("detection")
                    ->field(["items_id","d_id",'items_cate','is_pay'])
                    ->where(["d_id"=>$d_id])
                    ->find();
                if($detection["is_pay"]  == 0){ //0(免费)/1(付费)
                    $where      = ['o_state'=>'Y',"d_id"=>$d_id,"u_id"=>$u_id,'o_pay'=>1,"o_execute"=>1,'o_is_see'=>0];//如果是免费的肯定是查询成功的
                    $order      = Db::table("detection_order")
                        ->field(["o_number",'o_id'])
                        ->where($where)
                        ->order("o_create_time desc")
                        ->find();
                    $execute="N";
                    $isSee  =!empty($order)?"Y":"N";

                }else{
                    $where      = ['o_state'=>'Y',"d_id"=>$d_id,"u_id"=>$u_id,'o_pay'=>1,"o_execute"=>0];
                    $order      = Db::table("detection_order")
                        ->field(["o_number",'o_id'])
                        ->where($where)
                        ->order("o_create_time desc")
                        ->find();
                    $execute    =!empty($order)?"Y":"N";
                    $isSee      ="Y";
                    if(empty($order)){
                        $where      = ['o_state'=>'Y',"d_id"=>$d_id,"u_id"=>$u_id,'o_pay'=>1,"o_execute"=>1,'o_is_see'=>0];
                        $order      = Db::table("detection_order")
                            ->field(["o_number",'o_id'])
                            ->where($where)
                            ->order("o_create_time desc")
                            ->find();
                        $execute    ="N";
                        $isSee      =!empty($order)?"Y":"N";
                    }
                }
                $idstr=$order["o_id"];
                $data =["is_see"=>$isSee,"execute"=>$execute,"order"=>$order["o_number"],"idstr"=>$idstr];
                return CodeService::response(200,CodeService::SUCCESS,$data);
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function rest(){
//        功能包括：1检测订单是否有效--2.检测订单是否有同类历史未测报告--3.检测订单是否有同类完成报告
        try {
            if (request()->isPost()) {
                $order = input("order");
                $idstr = input("idstr");
                $o_id       = $idstr;
                if(empty($order) && empty($o_id)) return CodeService::DATA_RESULT_REFUND;
                if(!empty($order)){
                    $where["o_number"]=$order;
                }else if(!empty($o_id)){
                    $where["o_id"]    =$o_id;
                }
                //检测订单是否有效
                $order = Db::table("detection_order")->where($where)->find();
                $valid="N"; //默认无效
                if($order["o_pay"] == 1 && $order["o_execute"] == 0){
                    $valid="Y"; //有效订单
                }else
                    if($order["o_type"] == 2 && $order["o_pay"] == 0 && $order["o_execute"] == 0){
                        $valid="Y"; //有效订单
                    }
                $d_id=$order['d_id'];
                $u_id=$order['u_id'];
                $rel_execute=Db::table("detection_order")
                    ->where([
                        "u_id"=>$u_id,
                        'o_state'=>'Y',
                        'o_id'=>["not in",[$o_id]],
                        "d_id"=>$d_id,
                        "o_pay"=>1,
                        "o_execute"=>0])
                    ->find();
                $host_succsee=Db::table("detection_order")
                    ->where([
                        "u_id"=>$u_id,
                        'o_state'=>'Y',
                        'o_id'=>["not in",[$o_id]],
                        "d_id"=>$d_id,
                        "o_pay"=>1,
                        "o_execute"=>1])
                    ->find();
                $result=[
                    "valid"       =>$valid,
                    "host_execute"=>
                        !empty($rel_execute)?"Y":"N",
                    "host_execute_idstr"=>!empty($rel_execute)?$rel_execute["o_id"]:"",                                                 'host_execute_itemId'=>!empty($rel_execute)?json_decode($rel_execute['o_detection_json'],true)["items_id"]:0,
                    'host_execute_dId'=>!empty($rel_execute)?$rel_execute["d_id"]:"",

                    "host_succsee"=>!empty($host_succsee)?"Y":"N",
                    "host_succsee_idstr"=>!empty($host_succsee)?$host_succsee["o_id"]:"",
                    'host_succsee_itemId'=>!empty($host_succsee)?json_decode($host_succsee['o_detection_json'],true)["items_id"]:0,
                    'host_succsee_dId'=>!empty($host_succsee)?$host_succsee["d_id"]:"",
                ];
                return CodeService::response(200,CodeService::SUCCESS,$result);
            }else{
                return CodeService::REQUEST_METHOD_ERROR;
            }
        }catch (\Exception $e) {
            $msg = "Message：".$e->getMessage()."\t\r\nLine Number：".$e->getLine();
            return CodeService::response(500,$msg);
        }
    }
}
